package com.chenfan.filestore.config;

import com.alibaba.fastjson.JSONObject;
import com.chenfan.infra.constants.CommonBeanConstants;
import com.chenfan.infra.context.TenantContextHolder;
import com.chenfan.infra.context.UserContextHolder;
import com.chenfan.infra.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author K
 * @date 2021/1/20
 */
@Slf4j
@Component
public class PreFilter implements WebMvcConfigurer {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
                // 设置userVo，方便后面操作获取
                String token = request.getHeader(CommonBeanConstants.AUTHORIZATION);
                // FeignDebugContext.setHeader(token);
                // 设置对应的租户信息
                String tenantId = request.getHeader(CommonBeanConstants.TENANT_ID);
                log.info("从请求头中获取租户信息, 租户ID：{}", tenantId);
                if (!StringUtils.isEmpty(tenantId)) {
                    TenantContextHolder.setTenantId(Long.valueOf(tenantId));
                }
                if (StringUtils.isNotBlank(token)) {
                    UserVO attribute = JSONObject.parseObject(
                        stringRedisTemplate.opsForValue().get(CommonBeanConstants.AUTHORIZATION_TOKEN + ":" + token),
                        UserVO.class);
                    UserContextHolder.setUserVo(attribute);
                    UserContextHolder.setToken(token);
                    // 表明传递了Token但没传递租户信息
                    if (StringUtils.isEmpty(tenantId) && Objects.nonNull(attribute)) {
                        TenantContextHolder.setTenantId(attribute.getTenantId());
                    }
                }

                return true;
            }

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                Exception ex) {
                // 移除用户信息
                UserContextHolder.remove();
                TenantContextHolder.clear();
            }
        }).addPathPatterns("/**").excludePathPatterns("/verify_code");

    }
}
